﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Information.System.Hostd.Authorization;
using Information.System.Hostd.Extensions;
using Information.System.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Information.System.Model;
using Information.System.Model.Dto;
using Information.System.Model.View;
using Microsoft.Extensions.Logging;
using SqlSugar;
using Information.System.Model.Dto.System;
using Mapster;

namespace Information.System.Hostd.Controllers.System
{
    /// <summary>
    /// 字典接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DictionaryController : BaseController
    { 
        /// <summary>
      /// 会话管理接口
      /// </summary>
        private readonly TokenManager _tokenManager;
        /// <summary>
        /// 日志管理接口
        /// </summary>
        private readonly ILogger<DictionaryController> _logger;

        /// <summary>
        /// 字典接口
        /// </summary>
        private readonly ISysDictionaryService _dictionaryService;

        public DictionaryController(TokenManager tokenManager, ISysDictionaryService dictionaryService, ILogger<DictionaryController> logger)
        {
            _tokenManager = tokenManager;
            _dictionaryService = dictionaryService;
            _logger = logger;
        }

        /// <summary>
        /// 查询字典列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorization]
        public IActionResult Query(string name)
        {
            List<Sys_Dictionary> dictionarys = new List<Sys_Dictionary>();
            if (string.IsNullOrEmpty(name))
            {
                //获取系统所有菜单
                dictionarys = _dictionaryService.GetAll();

                return toResponse(ResolveTreeNodeVMSelect(dictionarys));
            }

            //开始拼装查询条件
            var predicate = Expressionable.Create<Sys_Dictionary>();

            predicate = predicate.And(m => m.Name.Contains(name)).Or(m=>m.Value.Contains(name));

            //获取系统所有字典
            var serachDictionary = _dictionaryService.GetWhere(predicate.ToExpression(), m => m.SortIndex);

            return toResponse(ResolveTreeNodeVMSelect(serachDictionary,"-1"));
        }

        /// <summary>
        /// 查询字典
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorization]
        public IActionResult Get(string id)
        {
            var response = _dictionaryService.GetId(id);

            return toResponse(response);
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorization(Power = "PRIV_DICTIONARY_CREATE")]
        public IActionResult Create([FromBody] DictionaryDto parm)
        {
            //从 Dto 映射到 实体
            var menu = parm.Adapt<Sys_Dictionary>();

            //如果 ParentID 是 -1 更新为 null
            menu.ParentID = menu.ParentID == "-1" ? null : menu.ParentID;

            menu.ToCreate(_tokenManager.GetSessionInfo());

            return toResponse(_dictionaryService.Add(menu));
        }

        /// <summary>
        /// 更新字典
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorization(Power = "PRIV_DICTIONARY_UPDATE")]
        public IActionResult Update([FromBody] DictionaryDto parm)
        {
            var userSession = _tokenManager.GetSessionInfo();

            parm.ParentID = parm.ParentID == "-1" ? null : parm.ParentID;

            return toResponse(_dictionaryService.Update(m => m.ID == parm.ID, m => new Sys_Dictionary()
            {
                Name = parm.Name,
                Value = parm.Value,
                ParentID = parm.ParentID,
                SortIndex = parm.SortIndex,
                Remark = parm.Remark,
                UpdateID = userSession.UserID,
                UpdateName = userSession.UserName,
                UpdateTime = DateTime.Now
            }));
        }
        /// <summary>
        /// 删除字典
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorization(Power = "PRIV_DICTIONARY_DELETE")]
        public IActionResult Delete(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return toResponse(StatusCodeType.Error, "删除字典 Id 不能为空");
            }

            bool hasChildren = _dictionaryService.Any(m => m.ParentID == id);

            if (hasChildren)
            {
                return toResponse(StatusCodeType.Error, "检测到下级含有子集，请先删除子集！");
            }

            var response = _dictionaryService.Delete(id);

            return toResponse(response);
        }

        private static List<TreeNodeVM> ResolveTreeNodeVMSelect(List<Sys_Dictionary> dicnarys, string parentId = null)
        {
            List<TreeNodeVM> resultMenus = new List<TreeNodeVM>();

            List<Sys_Dictionary> datalist = dicnarys;
            if (parentId != "-1") {
                datalist = dicnarys.Where(m => m.ParentID == parentId).OrderBy(m => m.SortIndex).ToList();
            }

            foreach (var dicnary in datalist)
            {
                var childrenDicnary = ResolveTreeNodeVMSelect(dicnarys, dicnary.ID);

                TreeNodeVM menusVM = new TreeNodeVM
                {
                    Id = dicnary.ID,
                    Name = dicnary.Name,
                    Open = false,
                    Value = dicnary.Value,
                    SortIndex = (int)dicnary.SortIndex,
                    ParentID = dicnary.ParentID,
                    Children = childrenDicnary.Count == 0 ? null : childrenDicnary

                };
                resultMenus.Add(menusVM);
            }

            return resultMenus;
        }
    }
}
